package com.nwpu.bigdata.cronJob;

import com.nwpu.bigdata.dao.mapper.FaultMapper;
import com.nwpu.bigdata.dao.mapper.RuleMapper;
import com.nwpu.bigdata.dto.BackendResult;
import com.nwpu.bigdata.model.Fault;
import com.nwpu.bigdata.model.Rule;
import com.nwpu.bigdata.model.RuleExample;
import com.nwpu.bigdata.service.FaultDetectionService;
import com.nwpu.bigdata.service.RuleDetectionService;
import com.nwpu.bigdata.service.RuleService;
import com.nwpu.bigdata.service.SendMailService;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时根据规则检查事件表，如果产生故障，向故障表写入故障数据
 *
 * @author carlin
 * @date 2018/7/30 0030 16:13
 */
@Component
@ImportResource(locations = {"classpath:/xmlConfig/spring/applicationContext-util.xml"})
public class FaultQuartzJob {

	private static Logger logger = LoggerFactory.getLogger(FaultQuartzJob.class);

	private final FaultDetectionService faultDetectionService;

	private final RuleMapper ruleMapper;

	@Value("${fault.dect.interval}")
	private String interval;

	private final SendMailService sendMailService;

	@Autowired
	public FaultQuartzJob(FaultDetectionService faultDetectionService, RuleMapper ruleMapper,
			SendMailService sendMailService) {
		this.faultDetectionService = faultDetectionService;
		this.ruleMapper = ruleMapper;
		this.sendMailService = sendMailService;
	}

	public void doFaultDetectionTask() {
		try {
			RuleExample ruleExample = new RuleExample();
			RuleExample.Criteria criteria = ruleExample.createCriteria();
			criteria.andIsEnabledEqualTo((byte) 1);
			List<Rule> rules = ruleMapper.selectByExample(ruleExample);
			for (Rule rule : rules) {
				faultDetectionService.faultDetection(rule, Long.parseLong(interval));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doDeleteIsAckFaults() {
		Long deleteNum = faultDetectionService.deleleFaultIsAck();
		logger.info("delete ack faults are {}", deleteNum);
	}

	public void doSendMailTask() {
		BackendResult<List<Fault>> backendResult = faultDetectionService.selectFaultByIsSent();
		if (backendResult.isSuccess()) {
			List<Fault> faults = backendResult.getData();
			for (Fault fault : faults) {
				System.out.println(ReflectionToStringBuilder.toString(fault));
				sendMailService.sendSimpleMail(fault.getSubject(), fault.getMessage(), fault.getSendTo());
				faultDetectionService.updateFaultStatusSent(fault.getId());
			}
		}
	}

}
